package com.alstudio.ui.module.setting;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.protocol.xmpp.ALXmlReader;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.module.local.Country;
import com.alstudio.pojo.module.local.Province;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.view.tableview.LocationItem;
import com.loovee.imaohu.R;

public class SelectRegionActivity extends TitleBarActivity {

	private LinearLayout mRegionLayout;

	private int level = 0;

	private ArrayList<Country> countryList;

	private Country mCountry;
	private Province mProvince;

	private ArrayList<String> cityArray = new ArrayList<String>();

	private ArrayList<Province> provinceArray = new ArrayList<Province>();

	// 显示国家
	private final int LEVEL_COUNTRY = 0;
	// 显示省份
	private final int LEVEL_PROVINCE = 1;
	// 显示城市
	private final int LEVEL_CITY = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		initData();
		// 显示地区
		showRegion();
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarContentView(R.layout.select_region_layout);
		setCenterTextViewMessage(R.string.TxtRegion);
		mRegionLayout = (LinearLayout) findViewById(R.id.region_list);

	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

		level = this.getIntent().getIntExtra("level", 1);
		mCountry = (Country) this.getIntent().getSerializableExtra("region");
		mProvince = (Province) this.getIntent()
				.getSerializableExtra("province");

		try {
			countryList = parseCountrys();

			mCountry = countryList.get(0);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		switch (level) {
		case LEVEL_COUNTRY:
			// 显示国家
			try {
				countryList = parseCountrys();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case LEVEL_PROVINCE:
			// 显示省份
			if (mCountry != null) {
				provinceArray = mCountry.getProvinceArray();
			}
			break;
		case LEVEL_CITY:
			// 显示城市
			if (mCountry != null) {
				if (mProvince != null) {
					cityArray = mProvince.getCityArray();
				}
			}

			break;
		}

	}

	private void showRegion() {
		switch (level) {
		case LEVEL_COUNTRY:
			// 显示国家
			showCountryList();
			break;
		case LEVEL_PROVINCE:
			// 显示省份
			showProvince();
			break;
		case LEVEL_CITY:
			// 显示城市
			showCity();
			break;
		}
	}

	private void showCountryList() {
		for (int i = 0; i < countryList.size(); i++) {
			updateUI(level, i, null, null);
		}
	}

	private void showProvince() {
		for (int i = 0; i < provinceArray.size(); i++) {
			updateUI(level, i, provinceArray.get(i).getProvince(),
					provinceArray.get(i));
		}
	}

	private void showCity() {
		for (int i = 0; i < cityArray.size(); i++) {
			updateUI(level, i, cityArray.get(i), null);
		}
	}

	private void updateUI(int level, final int position, final String region,
			final Province province) {
		LocationItem item = new LocationItem(this);

		int countrySize = 0;

		item.setGravity(Gravity.CENTER);

		switch (level) {
		case LEVEL_COUNTRY:
			// 显示国家
			Country country = countryList.get(position);
			item.mLocation.setText(country.getCountry());
			countrySize = countryList.size();
			break;
		case LEVEL_PROVINCE:
			// 显示省份
			if (!province.isThreeLevelEnable()) {
				item.mJumper.setVisibility(View.INVISIBLE);
			}
			countrySize = provinceArray.size();
			item.mLocation.setText(region);
			break;
		case LEVEL_CITY:
			// 显示城市
			countrySize = cityArray.size();
			item.mJumper.setVisibility(View.INVISIBLE);
			item.mLocation.setText(region);
			break;
		}

		item.setBackgroundResource(R.drawable.background_view_rounded_middle);

		mRegionLayout.addView(item);

		item.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent i = new Intent(SelectRegionActivity.this,
						SelectRegionActivity.class);
				switch (SelectRegionActivity.this.level) {
				case LEVEL_COUNTRY:
					// 跳转到省份
					i.putExtra("level", LEVEL_PROVINCE);
					mCountry = countryList.get(position);
					i.putExtra("region", mCountry);
					startActivityForResult(i, REQUEST_SELECT_CITY);
					break;
				case LEVEL_PROVINCE:
					// 跳转到城市
					if (province != null) {
						if (province.isThreeLevelEnable()) {
							i.putExtra("level", LEVEL_CITY);
							i.putExtra("region", mCountry);
							i.putExtra("province", mCountry.getProvinceArray()
									.get(position));
							startActivityForResult(i, REQUEST_SELECT_CITY);
						} else {
							// 没有城市可选，直接设定地区
							ALLocalEnv.getLocalEnv().getMyProfile()
									.setProvince(mCountry.getCountry());
							ALLocalEnv.getLocalEnv().getMyProfile()
									.setCity(province.getProvince());
							destroyAllSelectRegionActivity();
						}
					}

					break;
				case LEVEL_CITY:
					// 选择了城市
					ALLocalEnv.getLocalEnv().getMyProfile()
							.setProvince(mProvince.getProvince());
					ALLocalEnv.getLocalEnv().getMyProfile().setCity(region);
					destroyAllSelectRegionActivity();
					break;
				}

			}
		});
	}

	private void destroyAllSelectRegionActivity() {
		setResult(RESULT_OK);
		finish();
		// 保存个人资料
		User u = new User();
		u.setProvince(ALLocalEnv.getLocalEnv().getMyProfile().getProvince());
		u.setCity(ALLocalEnv.getLocalEnv().getMyProfile().getCity());
		ALUiXmppRequestCreator.postALUiXmppModifyUserProfileEvent(u);

	}

	private final int REQUEST_SELECT_CITY = 100;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if (requestCode != REQUEST_SELECT_CITY)
			return;
		if (resultCode == RESULT_OK)
			finish();
	}

	/******************************************** 以下为解析assert中的地区信息 ********************************************************/

	private ArrayList<Country> parseCountrys() throws IOException {

		InputStream is = null;
		ArrayList<Country> countryList = new ArrayList<Country>();

		try {
			is = this.getAssets().open("citys.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (is != null) {
			ALXmlReader reader = new ALXmlReader(is);

			Country mCountry = null;
			do {
				reader.next();
				if (reader.getType() == ALXmlReader.START_TAG) {

					if (reader.getName().equals("country")) {

						mCountry = new Country();
						// 读取到国家名
						mCountry.setCountry(reader.getAttribute("name"));
						ArrayList<Province> provinceList = new ArrayList<Province>();
						while (true) {
							reader.next();
							String tagname1 = reader.getName();
							if (tagname1 != null) {

								if ((reader.getType() == ALXmlReader.START_TAG)
										&& tagname1.equals("province")) {
									Province p = new Province();
									p.setProvince(reader.getAttribute("name"));
									// 解析省份
									ArrayList<String> cityList = new ArrayList<String>();
									String city = "";
									while (true) {
										reader.next();
										String tagname2 = reader.getName();
										if (tagname2 != null) {
											if ((reader.getType() == ALXmlReader.START_TAG)
													&& tagname2.equals("city")) {
												// 解析城市
												city = parseText(reader);
												if (city != null) {
													// 有三级菜单哦
													p.setThreeLevelEnable(true);
													cityList.add(city);
												}
											} else if (tagname2
													.equals("province")) {
												p.setCityArray(cityList);
												provinceList.add(p);
												break;
											}
										}
									}
								} else if ((reader.getType() == ALXmlReader.END_TAG)
										&& tagname1.equals("country")) {
									mCountry.setProvinceArray(provinceList);
									countryList.add(mCountry);
									break;
								}
							}
						}
					}
				}
			} while ((reader.getType() != ALXmlReader.END_TAG)
					|| (!reader.getName().equals("countrys")));

		}
		return countryList;
	}

	private String parseText(ALXmlReader reader) throws IOException {
		final String endTagName = reader.getName();
		final StringBuffer str = new StringBuffer("");
		int t = reader.next(); // omit start tag
		while (!endTagName.equals(reader.getName())) {
			if (t == ALXmlReader.TEXT) {
				str.append(reader.getText());
			}
			t = reader.next();
		}
		return str.toString();
	}


	private void doFinish() {
		if (level == LEVEL_CITY) {
			Intent i = null;
			i = new Intent();
			i.setClass(this, SelectRegionActivity.class);
			i.putExtra("level", 1);
			startActivity(i);
			return;
		}
		finish();
	}

}
